<template>
  <div class="whois-query-tool">
    <div class="tool-header">
      <h1>Whois查询</h1>
      <p>查询域名的注册信息</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 查询主体 -->
        <el-col :span="16">
          <div class="query-section">
            <!-- 查询输入 -->
            <div class="query-input">
              <h3>Whois查询</h3>
              <div class="input-group">
                <el-input
                  v-model="domainName"
                  placeholder="请输入域名，如：example.com"
                  size="large"
                  @keyup.enter="queryWhois"
                >
                  <template #prepend>
                    <el-icon><Search /></el-icon>
                  </template>
                  <template #append>
                    <el-button @click="queryWhois" type="primary" :loading="isQuerying" :disabled="!domainName.trim()">
                      查询
                    </el-button>
                  </template>
                </el-input>
              </div>
              
              <div class="quick-actions">
                <el-button @click="clearResult" size="small">
                  清空结果
                </el-button>
                <el-button @click="exportResult" size="small" :disabled="!queryResult">
                  导出结果
                </el-button>
              </div>
            </div>
            
            <!-- 查询结果 -->
            <div class="query-result" v-if="queryResult">
              <h3>查询结果</h3>
              <div class="result-tabs">
                <el-tabs v-model="activeTab" type="card">
                  <el-tab-pane label="基本信息" name="basic">
                    <div class="basic-info">
                      <div class="info-grid">
                        <div class="info-item">
                          <div class="info-label">域名</div>
                          <div class="info-value">{{ queryResult.domain }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">注册商</div>
                          <div class="info-value">{{ queryResult.registrar }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">注册时间</div>
                          <div class="info-value">{{ queryResult.creationDate }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">到期时间</div>
                          <div class="info-value">{{ queryResult.expirationDate }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">更新时间</div>
                          <div class="info-value">{{ queryResult.updatedDate }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">状态</div>
                          <div class="info-value">
                            <el-tag v-for="status in queryResult.status" :key="status" size="small" type="success">
                              {{ status }}
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="注册信息" name="registrant">
                    <div class="registrant-info">
                      <div class="info-grid">
                        <div class="info-item">
                          <div class="info-label">注册人</div>
                          <div class="info-value">{{ queryResult.registrant.name || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">组织</div>
                          <div class="info-value">{{ queryResult.registrant.organization || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">邮箱</div>
                          <div class="info-value">{{ queryResult.registrant.email || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">电话</div>
                          <div class="info-value">{{ queryResult.registrant.phone || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">地址</div>
                          <div class="info-value">{{ queryResult.registrant.address || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">城市</div>
                          <div class="info-value">{{ queryResult.registrant.city || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">省份</div>
                          <div class="info-value">{{ queryResult.registrant.state || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">国家</div>
                          <div class="info-value">{{ queryResult.registrant.country || '隐私保护' }}</div>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="技术信息" name="technical">
                    <div class="technical-info">
                      <div class="info-grid">
                        <div class="info-item">
                          <div class="info-label">技术联系人</div>
                          <div class="info-value">{{ queryResult.technical.name || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">技术邮箱</div>
                          <div class="info-value">{{ queryResult.technical.email || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">技术电话</div>
                          <div class="info-value">{{ queryResult.technical.phone || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">管理联系人</div>
                          <div class="info-value">{{ queryResult.admin.name || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">管理邮箱</div>
                          <div class="info-value">{{ queryResult.admin.email || '隐私保护' }}</div>
                        </div>
                        <div class="info-item">
                          <div class="info-label">管理电话</div>
                          <div class="info-value">{{ queryResult.admin.phone || '隐私保护' }}</div>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="DNS信息" name="dns">
                    <div class="dns-info">
                      <div class="dns-section">
                        <h4>Name Servers</h4>
                        <div class="dns-list">
                          <div v-for="ns in queryResult.nameServers" :key="ns" class="dns-item">
                            {{ ns }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-tab-pane>
                  
                  <el-tab-pane label="原始数据" name="raw">
                    <div class="raw-data">
                      <el-input
                        v-model="queryResult.rawData"
                        type="textarea"
                        :rows="20"
                        readonly
                        placeholder="原始Whois数据"
                      />
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
            
            <!-- 查询历史 -->
            <div class="query-history">
              <h3>查询历史</h3>
              <div class="history-list">
                <div 
                  v-for="(item, index) in queryHistory" 
                  :key="index"
                  class="history-item"
                  @click="loadFromHistory(item)"
                >
                  <div class="history-domain">{{ item.domain }}</div>
                  <div class="history-info">
                    <span class="history-registrar">{{ item.registrar }}</span>
                    <span class="history-date">{{ item.date }}</span>
                  </div>
                </div>
                <div v-if="queryHistory.length === 0" class="empty-history">
                  暂无查询历史
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 工具和说明 -->
        <el-col :span="8">
          <div class="tools-section">
            <div class="section-header">
              <h3>常用域名</h3>
            </div>
            
            <div class="common-domains">
              <div 
                v-for="domain in commonDomains" 
                :key="domain.domain"
                class="domain-item"
                @click="setDomain(domain.domain)"
              >
                <div class="domain-name">{{ domain.domain }}</div>
                <div class="domain-description">{{ domain.description }}</div>
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>查询信息：</h4>
                <ul>
                  <li><strong>基本信息：</strong> 域名、注册商、注册时间等</li>
                  <li><strong>注册信息：</strong> 注册人、组织、联系方式等</li>
                  <li><strong>技术信息：</strong> 技术联系人、管理联系人等</li>
                  <li><strong>DNS信息：</strong> 域名服务器信息</li>
                  <li><strong>原始数据：</strong> 完整的Whois记录</li>
                </ul>
                
                <h4>支持域名：</h4>
                <ul>
                  <li>通用顶级域名 (.com, .org, .net)</li>
                  <li>国家顶级域名 (.cn, .uk, .de)</li>
                  <li>新通用顶级域名 (.app, .blog, .shop)</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 某些域名可能启用隐私保护</p>
                  <p>⚠️ 查询结果可能因注册商而异</p>
                  <p>⚠️ 请遵守相关法律法规</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

const domainName = ref('')
const isQuerying = ref(false)
const queryResult = ref(null)
const activeTab = ref('basic')
const queryHistory = ref([])

const commonDomains = [
  { domain: 'google.com', description: 'Google' },
  { domain: 'baidu.com', description: '百度' },
  { domain: 'qq.com', description: '腾讯' },
  { domain: 'taobao.com', description: '淘宝' },
  { domain: 'jd.com', description: '京东' },
  { domain: 'sina.com.cn', description: '新浪' }
]

const validateDomain = (domain) => {
  const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])*$/
  return domainRegex.test(domain)
}

const queryWhois = async () => {
  if (!domainName.value.trim()) {
    ElMessage.warning('请输入域名')
    return
  }
  
  let domain = domainName.value.trim().toLowerCase()
  if (!domain.startsWith('http://') && !domain.startsWith('https://')) {
    domain = domain.replace(/^www\./, '')
  } else {
    try {
      const url = new URL(domain)
      domain = url.hostname.replace(/^www\./, '')
    } catch {
      ElMessage.error('请输入有效的域名')
      return
    }
  }
  
  if (!validateDomain(domain)) {
    ElMessage.error('请输入有效的域名')
    return
  }
  
  isQuerying.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 模拟查询结果
    const mockResult = {
      domain: domain,
      registrar: 'GoDaddy.com, LLC',
      creationDate: '2020-01-15T10:30:00Z',
      expirationDate: '2025-01-15T10:30:00Z',
      updatedDate: '2023-06-20T14:22:00Z',
      status: ['clientTransferProhibited', 'clientUpdateProhibited'],
      registrant: {
        name: 'Privacy Protection Service',
        organization: 'Privacy Protection Service Inc.',
        email: 'privacy@example.com',
        phone: '+1.1234567890',
        address: '123 Privacy St',
        city: 'Privacy City',
        state: 'PC',
        country: 'US'
      },
      technical: {
        name: 'Technical Contact',
        email: 'tech@example.com',
        phone: '+1.1234567890'
      },
      admin: {
        name: 'Admin Contact',
        email: 'admin@example.com',
        phone: '+1.1234567890'
      },
      nameServers: [
        'ns1.example.com',
        'ns2.example.com'
      ],
      rawData: `Domain Name: ${domain}
Registry Domain ID: 1234567890-COM
Registrar WHOIS Server: whois.godaddy.com
Registrar URL: http://www.godaddy.com
Updated Date: 2023-06-20T14:22:00Z
Creation Date: 2020-01-15T10:30:00Z
Registry Expiry Date: 2025-01-15T10:30:00Z
Registrar: GoDaddy.com, LLC
Registrar IANA ID: 146
Registrar Abuse Contact Email: abuse@godaddy.com
Registrar Abuse Contact Phone: +1.4806242505
Domain Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited
Domain Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited
Name Server: ns1.example.com
Name Server: ns2.example.com
DNSSEC: unsigned`
    }
    
    queryResult.value = mockResult
    
    // 添加到历史
    addToHistory(mockResult)
    
    ElMessage.success('查询成功')
    
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    isQuerying.value = false
  }
}

const clearResult = () => {
  queryResult.value = null
  domainName.value = ''
  activeTab.value = 'basic'
  ElMessage.info('已清空结果')
}

const exportResult = () => {
  if (!queryResult.value) return
  
  const data = JSON.stringify(queryResult.value, null, 2)
  const blob = new Blob([data], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `whois-${queryResult.value.domain}.json`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('结果已导出')
}

const addToHistory = (result) => {
  const historyItem = {
    domain: result.domain,
    registrar: result.registrar,
    date: new Date().toLocaleString('zh-CN')
  }
  
  queryHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (queryHistory.value.length > 20) {
    queryHistory.value = queryHistory.value.slice(0, 20)
  }
}

const loadFromHistory = (item) => {
  domainName.value = item.domain
  ElMessage.success(`已加载：${item.domain}`)
}

const setDomain = (domain) => {
  domainName.value = domain
  ElMessage.success(`已设置域名：${domain}`)
}
</script>

<style scoped>
.whois-query-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.query-section,
.tools-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.query-input,
.query-result,
.query-history {
  margin-bottom: 30px;
}

.query-input h3,
.query-result h3,
.query-history h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.input-group {
  margin-bottom: 15px;
}

.quick-actions {
  display: flex;
  gap: 10px;
}

.result-tabs {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.basic-info,
.registrant-info,
.technical-info,
.dns-info {
  padding: 20px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.info-item {
  background: white;
  border-radius: 6px;
  padding: 15px;
  border: 1px solid #e9ecef;
}

.info-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.info-value {
  font-size: 1rem;
  color: #333;
  word-break: break-all;
}

.dns-section {
  margin-bottom: 20px;
}

.dns-section h4 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.1rem;
}

.dns-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.dns-item {
  background: white;
  border-radius: 6px;
  padding: 12px;
  border: 1px solid #e9ecef;
  font-family: 'Courier New', monospace;
  color: #333;
}

.raw-data {
  padding: 20px 0;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.history-domain {
  font-size: 1rem;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.history-info {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: #666;
}

.history-registrar {
  color: #667eea;
  font-weight: 500;
}

.history-date {
  color: #999;
}

.empty-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-style: italic;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.common-domains {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.domain-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.domain-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.domain-name {
  font-size: 1rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.domain-description {
  font-size: 0.9rem;
  color: #666;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .history-info {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
